local WorkStation = require'entities.workstation'

local FuelCell = {}
FuelCell.mt = { __index = FuelCell }
setmetatable( FuelCell, WorkStation.mt )


function  FuelCell.initialize( x, y, ship )
	
	local FC = {}
	
	FC.sup_stat = -7
	
	local res = {
		{ name = 'power', current = 100, max = 100, min = 0, rate = FC.sup_stat, sup_rate = -1 },
	
	}
	
	local req = {
		[1] = function(self)
			if self.powered then return true end		
		end,
	
	}
	
	FC = WorkStation.new('fuel_cell', x, y, 100, 'fuel_cell', ship, res, req)	
	FC.connections = {}
	FC.c_id = {}
	
	FC.x = x
	FC.y = y
	
	
	
	
	
	return FC
end

function FuelCell:make_map()
	
	self.map = {}
	self.map[WIRE_TYPE] = self.ship.network_map[WIRE_TYPE]

end


function FuelCell.new( x, y, ship )
	local o = FuelCell.initialize( x, y, ship )
	
	
	return o
end

function FuelCell:connect( station )
	-- adds connections to other stations
	if not self.connections then self.connections = {} end
	
	
	local iter = #self.connections+1
	
	self.connections[iter] = station
	self.c_id[iter] = true
	if station.res[RES_POWER] then
		station.res[RES_POWER].pow_rate = self.res[RES_POWER].sup_rate
	end

end


function FuelCell:test_connections()

	if not self.connections then 
		print("FUEL CELL ERROR no connections"); 
		return nil 
	end
	
	
	local connection_test = function(fc, c, c_id)
		--require('mobdebug').on() -- zerobrane
		local a
		if c.ship.network_map then
			local nm = c.ship.network_map[WIRE_TYPE]
			fc.grid = jGrid(nm)
			fc.path = jPath(fc.grid, 'JPS', WALKABLE_TILE)
			fc.path:setMode('ORTHOGONAL')
			
			-- tile of station
			local tx = c.x/TILE_SIZE
			local ty = c.y/TILE_SIZE
			local fx = fc.x/TILE_SIZE
			local fy = fc.y/TILE_SIZE
			
			local path = fc.path:getPath(fx, fy, tx, ty)
			
			if path then 
				fc.c_id[c_id] = true
				c.powered = true
				c.res.pow_rate = fc.res.sup_rate
			else 
				fc.c_id[c_id] = false
				--[[print("FUEL_CELL conn_test path not found")]]
				c.powered = false
			end
		
		end
	
	end
	
	
	
	local sc = self.connections
	
	for i = 1, #sc do
		
		local a = MOAICoroutine.new()
		
		a:run(connection_test, self, sc[i], i)
		
	
	end

end



return FuelCell